import GoodsItem from './GoodsItem'

/**
 * 管理购物车中商品数据的模型
 */
export default class GoodsModel {
  cart: GoodsItem[] // 购物车中的商品数组
  total: number // 待结算商品的总金额
  isAllChecked: boolean // 是否全部选中
  allAmount: number // 购物车中总商品数量

  constructor() {
    // 初始化购物车中几项商品数据
    this.cart = [
      new GoodsItem(
        'Watch GT4',
        'https://res5.vmallres.com/pimages//uomcdn/CN/pms/202403/gbom/6942103118470/800_800_7423E5BF86A212CA0473FBA205E1FAD3mp.png',
        1338
      ),
      new GoodsItem(
        'Free buds pro 3',
        'https://res4.vmallres.com/pimages//uomcdn/CN/pms/202309/gbom/6942103106217/800_800_BA91CA59194C170E813C8B5208710D9Fmp.png',
        1399
      ),
      new GoodsItem(
        'Mate Pad Pro',
        'https://res8.vmallres.com/pimages//uomcdn/CN/pms/202404/gbom/6942103108914/800_800_F12CF22BD7473D674DB46D2C7EF95D58mp.png',
        5199
      )
    ]
    // 计算各项初始数据
    this.summary()
  }

  /**
   * 统计购物车数组中各项数据
   */
  summary() {
    // 总金额
    this.total = this.cart.reduce((sum, goods) => {
      // return goods.checked ? sum + goods.price * goods.amount : sum
      if (goods.checked) {
        return sum + goods.price * goods.amount
      }
      return sum
    }, 0)
    // 是否已全选
    this.isAllChecked = this.cart.every(goods => goods.checked)
    // 购物车中总商品数量
    this.allAmount = this.cart.reduce((sum, goods) => sum + goods.amount, 0)
  }

  /**
   * 切换购物车中所有商品的选中状态
   * @param checked
   */
  toggleAllChecked(checked: boolean) {
    this.cart = this.cart.map(goods => {
      goods.toggle(checked)
      return goods
    })
    this.summary()
  }
}